/**
 * Created by hubery on 2017/8/8.
 */

/***
 * cookie操作集合
 * @type {{get: ((key)=>*), set: ((key, value, time)), delete: ((key))}}
 */
export var CookieStorage = {
  /***
   * 获取cookie
   * @param key 键
   * @returns {*}
   */
  get (key) {
    let cookie = document.cookie.replace(/[ ]/g, ''); // 格式化cookie，删除所有空格
    let cookieKeyValues = cookie.split(';'); // 使用符号";" 分割cookie
    let cookieValue;
    for (let i = 0; i < cookieKeyValues.length; i++) {
      let cookieKeyValue = cookieKeyValues[i].split('=');
      if (cookieKeyValue[0] === key) {
        cookieValue = cookieKeyValue[1];
      }
    }
    return cookieValue;
  },
  /***
   * 设置cookie
   * @param key 键
   * @param value 值
   * @param time 过期时间间隔（天）
   */
  set (key, value, time) {
    let date = new Date();
    date.setTime(date.getTime() + time * 24 * 3600 * 1000);
    document.cookie = key + '=' + value + ';expires=' + date.toUTCString();
  },
  /***
   * 删除cookie
   * @param key 键
   */
  delete (key) {
    let date = new Date();
    date.setTime(date.getTime() - 1000);
    document.cookie = key + '=invalid;expires=' + date.toUTCString();
  }
};
